package com.example.temp.controller;

import com.example.temp.dto.ClassResultsDTO;
import com.example.temp.entity.ClassEntity;
import com.example.temp.entity.Question;
import com.example.temp.entity.Result;
import com.example.temp.entity.Student;
import com.example.temp.mapper.ClassMapper;
import com.example.temp.mapper.QuestionMapper;
import com.example.temp.mapper.ResultMapper;
import com.example.temp.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.xml.ws.Response;
import org.springframework.jdbc.core.JdbcTemplate;

@RestController
@RequestMapping("/result")
@CrossOrigin  // 允许跨域请求
public class ResultController {

    @Autowired
    private ResultMapper resultMapper;

    @Autowired
    private QuestionMapper questionMapper;
    
    @Autowired
    private ClassMapper classMapper;
    
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 获取所有结果
    @GetMapping("/all")
    public ResponseEntity<List<Result>> getAllResults() {
        List<Result> results = resultMapper.findAll();
        if (results == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(results);
    }
    
    // 根据ID获取结果
    @GetMapping("/{id}")
    public ResponseEntity<Result> getResultById(@PathVariable Integer id) {
        Result result = resultMapper.findById(id);
        if (result == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(result);
    }

    // 根据教师id获取结果，按班级分组
    @GetMapping("/teacher")
    public ResponseEntity<?> getResultsByTeacherId(@RequestParam String teacherId) {
        // 验证教师ID是否为空
        System.out.println("教师ID:"+teacherId);
        if (teacherId == null || teacherId.isEmpty()) {
            return ResponseEntity.badRequest().build();
        }
        // 验证教师ID是否为数字
        if (!teacherId.matches("\\d+")) {
            return ResponseEntity.badRequest().build();
        }
        
        try {
            // 获取教师负责的所有班级
            List<ClassEntity> teacherClasses = classMapper.findByTeacherId(teacherId);
            if (teacherClasses.isEmpty()) {
                return ResponseEntity.ok(new ArrayList<>()); // 教师没有负责的班级，返回空列表
            }
            
            // 获取教师id对应的题目
            List<Question> questions = questionMapper.findByTeacherId(teacherId);
            if (questions.isEmpty()) {
                return ResponseEntity.ok(new ArrayList<>()); // 教师没有发布题目，返回空列表
            }
            
            // 获取这些题目对应的所有测试结果
            List<Result> allResults = resultMapper.findByQuestionId(
                questions.stream().map(Question::getId).collect(Collectors.toList())
            );
            
            if (allResults.isEmpty()) {
                return ResponseEntity.ok(new ArrayList<>()); // 没有测试结果，返回空列表
            }
            
            // 按班级分组结果数据
            Map<Integer, ClassResultsDTO> classResultsMap = new HashMap<>();
            
            // 为每个班级创建初始的DTO对象
            for (ClassEntity classEntity : teacherClasses) {
                ClassResultsDTO dto = new ClassResultsDTO();
                dto.setClassId(classEntity.getClassId());
                dto.setClassName(classEntity.getClassName());
                dto.setResults(new ArrayList<>());
                classResultsMap.put(classEntity.getClassId(), dto);
            }
            
            // 遍历所有结果，按班级分组
            for (Result result : allResults) {
                // 根据学生ID获取学生信息
                Student student = studentMapper.findByID(result.getStudentId());
                if (student != null && student.getClassId() != null) {
                    // 确认学生所在班级属于该教师
                    if (classResultsMap.containsKey(student.getClassId())) {
                        // 将结果添加到对应班级的结果列表中
                        classResultsMap.get(student.getClassId()).getResults().add(result);
                    }
                }
            }
            
            // 移除没有结果的班级
            List<ClassResultsDTO> resultsList = classResultsMap.values().stream()
                .filter(dto -> !dto.getResults().isEmpty())
                .collect(Collectors.toList());
            
            return ResponseEntity.ok(resultsList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("获取数据时发生错误: " + e.getMessage());
        }
    }
    
    // 根据学生ID获取结果
    @GetMapping("/student")
    public ResponseEntity<List<Map<String, Object>>> getResultsByStudentId(@RequestParam String studentId) {
        try {
            // 验证参数
            if (studentId == null || studentId.trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }
            
            System.out.println("获取学生测试数据 - studentId: " + studentId);
            
            // 第一步：根据studentId在student表找到classId
            Student student = studentMapper.findByID(studentId);
            if (student == null) {
                System.out.println("未找到学生信息: " + studentId);
                return ResponseEntity.ok(new ArrayList<>());
            }
            
            Integer classId = student.getClassId();
            if (classId == null) {
                System.out.println("学生未分配班级: " + studentId);
                return ResponseEntity.ok(new ArrayList<>());
            }
            
            // 第二步：通过classId在class表找到className
            ClassEntity classEntity = classMapper.findById(classId);
            if (classEntity == null) {
                System.out.println("未找到班级信息: " + classId);
                return ResponseEntity.ok(new ArrayList<>());
            }
            
            String className = classEntity.getClassName();
            System.out.println("找到班级: " + className);
            
            // 第三步：通过className在result_name表找到对应班级的记录
            List<Map<String, Object>> resultNameRecords = jdbcTemplate.queryForList(
                "SELECT result_id, result_name, class_name FROM result_name WHERE class_name = ?",
                className
            );
            
            if (resultNameRecords.isEmpty()) {
                System.out.println("未找到该班级的测试记录: " + className);
                return ResponseEntity.ok(new ArrayList<>());
            }
            
            // 第四步：构建三元数组结构：班级 -> result_name -> result
            List<Map<String, Object>> classStructure = new ArrayList<>();
            
            // 创建班级对象
            Map<String, Object> classInfo = new HashMap<>();
            classInfo.put("classId", classId);
            classInfo.put("className", className);
            classInfo.put("tests", new ArrayList<>());
            
            for (Map<String, Object> resultNameRecord : resultNameRecords) {
                String resultIds = (String) resultNameRecord.get("result_id");
                String testName = (String) resultNameRecord.get("result_name");
                
                // 创建测试对象
                Map<String, Object> testInfo = new HashMap<>();
                testInfo.put("testName", testName);
                testInfo.put("results", new ArrayList<>());
                
                if (resultIds != null && !resultIds.trim().isEmpty()) {
                    // 解析result_id字符串（逗号分隔）
                    String[] ids = resultIds.split(",");
                    
                    // 获取该测试的所有result记录
                    String resultSql = "SELECT * FROM results WHERE id IN (" + 
                        String.join(",", ids) + ") AND student_id = ? ORDER BY id";
                    
                    List<Result> testResults = jdbcTemplate.query(resultSql, 
                        new Object[]{studentId}, 
                        (rs, rowNum) -> {
                            Result result = new Result();
                            result.setId(rs.getInt("id"));
                            result.setStudentId(rs.getString("student_id"));
                            result.setQuestionId(rs.getInt("question_id"));
                            result.setScore(rs.getInt("score"));
                            result.setMaxScore(rs.getInt("max_score"));
                            result.setStartTime(rs.getTimestamp("start_time"));
                            result.setEndTime(rs.getTimestamp("end_time"));
                            result.setAnswerTime(rs.getInt("answer_time"));
                            result.setPurpose(rs.getString("purpose"));
                            result.setIsSubmit(rs.getString("is_submit"));
                            result.setIsCorrect(rs.getString("is_correct"));
                            result.setComment(rs.getString("comment"));
                            result.setAnswer(rs.getString("answer"));
                            return result;
                        });
                    
                    // 将result添加到测试对象中
                    testInfo.put("results", testResults);
                }
                
                // 将测试对象添加到班级对象中
                ((List<Map<String, Object>>) classInfo.get("tests")).add(testInfo);
            }
            
            // 将班级对象添加到结果列表中
            classStructure.add(classInfo);
            
            System.out.println("成功获取学生测试数据，班级: " + className + ", 测试数量: " + resultNameRecords.size());
            return ResponseEntity.ok(classStructure);
            
        } catch (Exception e) {
            System.err.println("获取学生测试数据失败: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 根据学生ID和测试发布ID获取完整的问题详情
     * @param studentId 学生ID
     * @param examPublish 测试发布ID
     * @return 包含完整问题详情的响应
     */
    @GetMapping("/studentExamDetails")
    public ResponseEntity<?> getDetailsByStudentAndExam(
            @RequestParam String studentId,
            @RequestParam Integer examPublish) {
        try {
            // 验证参数是否合法
            if (studentId == null || studentId.trim().isEmpty() || examPublish == null) {
                Map<String, String> errorResponse = new HashMap<>();
                errorResponse.put("message", "学生ID或测试ID不能为空");
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
            }
            
            // 打印请求参数，方便调试
            System.out.println("获取学生测试详情 - studentId: " + studentId + ", examPublish: " + examPublish);
            
            try {
                // 第一步：获取results表中的记录
                List<Result> results = resultMapper.findResultsByStudentAndExam(studentId, examPublish);
                if (results == null || results.isEmpty()) {
                    Map<String, String> errorResponse = new HashMap<>();
                    errorResponse.put("message", "未找到该学生的测试结果");
                    return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse);
                }
                
                // 第二步：为每个result获取对应的问题详情
                List<Map<String, Object>> detailedResults = new ArrayList<>();
                for (Result result : results) {
                    // 获取问题详情
                    Map<String, Object> questionDetails = null;
                    try {
                        Question question = questionMapper.getByID(result.getQuestionId());
                        if (question != null) {
                            questionDetails = new HashMap<>();
                            questionDetails.put("text", question.getQuestionText());
                            questionDetails.put("type", question.getType());
                            //questionDetails.put("picture", question.getImageUrl());
                            questionDetails.put("answer", question.getAnswer());
                        }
                    } catch (Exception e) {
                        System.err.println("获取问题详情失败，questionId: " + result.getQuestionId() + ", 错误: " + e.getMessage());
                    }
                    
                    // 创建包含result和question详情的综合对象
                    Map<String, Object> detailedResult = new HashMap<>();
                    
                    // 添加result的所有字段
                    detailedResult.put("examId", result.getId());
                    //detailedResult.put("examPublish", result.getExamPublish());
                    detailedResult.put("studentId", result.getStudentId());
                    detailedResult.put("questionId", result.getQuestionId());
                    detailedResult.put("score", result.getScore());
                    detailedResult.put("actualScore", result.getScore()); // 用相同字段作为实际得分
                    detailedResult.put("startTime", result.getStartTime());
                    detailedResult.put("endTime", result.getEndTime());
                    detailedResult.put("answerTime", result.getAnswerTime());
                    detailedResult.put("purpose", result.getPurpose());
                    detailedResult.put("answer", result.getAnswer());
                    
                    // 如果找到问题详情，添加问题相关字段
                    if (questionDetails != null) {
                        detailedResult.put("questionText", questionDetails.get("text"));
                        detailedResult.put("type", questionDetails.get("type"));
                        detailedResult.put("imageUrl", questionDetails.get("picture"));
                        detailedResult.put("correctAnswer", questionDetails.get("answer"));
                    }
                    
                    detailedResults.add(detailedResult);
                }
                
                return ResponseEntity.ok(detailedResults);
            } catch (Exception e) {
                // 打印详细的SQL错误信息
                System.err.println("SQL执行错误: " + e.getMessage());
                e.printStackTrace();
                throw e; // 重新抛出异常以便外层catch捕获
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "获取数据时发生错误: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }
    }
    
    // 更新结果
    @PutMapping("/update")
    public ResponseEntity<Void> updateResult(@RequestBody Result[] results) {
        // 验证必要的字段是否存在
        for (Result result : results) {
            if (result.getId() <= 0 || result.getStudentId() == null || result.getQuestionId() <= 0) {
                return ResponseEntity.badRequest().build();
            }
        }
        
        resultMapper.update(results);
        return ResponseEntity.ok().build();
    }
    
    // 更新答案字段
    @PutMapping("/updateanswer")
    public ResponseEntity<Map<String, Object>> updateAnswers(@RequestBody Result[] results) {
        // 验证必要的字段是否存在
        for (Result result : results) {
            if (result.getId() <= 0 || result.getStudentId() == null || result.getQuestionId() <= 0) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("message", "必填字段缺失");
                return ResponseEntity.badRequest().body(response);
            }
        }
        
        try {
            // 更新answer字段和is_submit字段
            int successCount = 0;
            for (Result result : results) {
                System.out.println("*****************************************更新答案和提交状态: " + result);
                int updated = resultMapper.updateAnswerAndSubmit(result);
                if (updated > 0) {
                    successCount++;
                } else {
                    System.out.println("更新失败，未找到匹配的记录: " + result);
                }
            }
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "更新成功，共更新 " + successCount + " 条记录");
            response.put("successCount", successCount);
            response.put("totalCount", results.length);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    // 更新score字段
    @PostMapping("/updatescoreandcomment")
    public ResponseEntity<Map<String, Object>> updateScores(@RequestBody List<Map<String, Object>> results) {
        // 验证请求数据
        if (results == null || results.isEmpty()) {
            Map<String, Object> response = new HashMap<>();
            response.put("code", 400);
            response.put("message", "请求数据为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        try {
            // 打印接收到的数据，方便调试
            System.out.println("接收到评分更新请求: " + results.size() + "条数据");
            System.out.println("接收到评分更新请求: " + results);
            for (Map<String, Object> resultData : results) {
                try {
                    // 提取必要字段
                    Integer questionId = null;
                    String studentId = null;
                   // Integer examPublish = null;
                    Integer Id = null;
                    
                    try {
                        // 1. 先获取examId，因为其他字段可能需要它
                        Object IdObj = resultData.get("id");
                        if (IdObj instanceof Integer) {
                            Id = (Integer) IdObj;
                        } else if (IdObj instanceof String) {
                            Id = Integer.parseInt(((String) IdObj).trim());
                        } else if (IdObj instanceof Double) {
                            Id = ((Double) IdObj).intValue();
                        }
                        
                        System.out.println("处理评分更新 - Id: " + Id);
                        
                        // 2. 安全地获取和转换questionId
                        Object questionIdObj = resultData.get("questionId");
                        if (questionIdObj instanceof Integer) {
                            questionId = (Integer) questionIdObj;
                        } else if (questionIdObj instanceof String) {
                            questionId = Integer.parseInt(((String) questionIdObj).trim());
                        } else if (questionIdObj instanceof Double) {
                            questionId = ((Double) questionIdObj).intValue();
                        }
                        
                        // 3. 安全地获取studentId
                        Object studentIdObj = resultData.get("studentId");
                        if (studentIdObj instanceof String) {
                            studentId = (String) studentIdObj;
                        } else if (studentIdObj != null) {
                            studentId = String.valueOf(studentIdObj);
                        }
                        
                        // examPublish 已弃用，不再处理
                    } catch (NumberFormatException e) {
                        System.err.println("数值转换错误: " + e.getMessage());
                        throw new RuntimeException("数值转换错误", e);
                    }
                    
                    // 验证必要字段是否存在
                    if (questionId == null || studentId == null) {
                        System.err.println("必要字段缺失 - questionId: " + questionId + 
                                          ", studentId: " + studentId);
                        throw new RuntimeException("必要字段缺失，需要 questionId 和 studentId");
                    }
                    
                    // 从actualScore获取分数值
                    Object actualScoreObj = resultData.get("actualScore");
                    int score = 0;
                    if (actualScoreObj instanceof Integer) {
                        score = (Integer) actualScoreObj;
                    } else if (actualScoreObj instanceof Double) {
                        score = ((Double) actualScoreObj).intValue();
                    } else if (actualScoreObj instanceof String) {
                        try {
                            score = Integer.parseInt((String) actualScoreObj);
                        } catch (NumberFormatException e) {
                            System.err.println("分数转换错误: " + e.getMessage());
                            // 设置默认值为0，继续处理而不抛出异常
                            score = 0;
                        }
                    }
                    
                    // 获取评语
                    String comment = null;
                    Object commentObj = resultData.get("comment");
                    if (commentObj instanceof String) {
                        comment = (String) commentObj;
                    } else if (commentObj != null) {
                        comment = String.valueOf(commentObj);
                    }
                    
                    // 打印详细日志
                    System.out.println("更新分数 - Id: " + Id + 
                                       ", studentId: " + studentId + 
                                       ", questionId: " + questionId + 
                                       ", score: " + score + 
                                       ", comment: " + comment);
                    
                    // 创建Result对象
                    Result result = new Result();
                    // examId 是可选的，只在不为null时设置
                    if (Id != null) {
                        result.setId(Id);
                    }
                    result.setStudentId(studentId);
                    result.setQuestionId(questionId);
                    result.setScore(score);  // 设置分数
                    
                    // 确保comment不为null
                    if (comment == null) {
                        comment = "";
                    }
                    
                    // 打印更多详细数据，帮助调试
                    System.out.println("创建的Result对象: " + result);
                    
                    try {
                        // 使用新的方法同时更新分数、评语和is_correct字段
                        System.out.println("正在更新分数、评语和批改状态...");
                        result.setComment(comment);
                        int updated = resultMapper.updateScoreCommentAndCorrect(result);
                        if (updated > 0) {
                            System.out.println("分数、评语和批改状态更新成功!");
                        } else {
                            System.err.println("警告：未找到匹配的记录！更新失败");
                            Map<String, Object> errorResponse = new HashMap<>();
                            errorResponse.put("code", 500);
                            errorResponse.put("message", "未找到匹配的记录，更新失败");
                            throw new RuntimeException("未找到匹配的记录");
                        }
                    } catch (Exception e) {
                        System.err.println("处理单条记录时出错: " + e.getMessage());
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    System.err.println("处理单条记录时出错: " + e.getMessage());
                    e.printStackTrace();
                }
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> response = new HashMap<>();
            response.put("code", 500);
            response.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}
